package com.ebraga.trackerclub.android.view;

import java.util.Date;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.webkit.WebView;

import com.ebraga.trackerclub.android.R;
import com.ebraga.trackerclub.android.exception.AndroidViewException;
import com.ebraga.trackerclub.android.exception.handler.BackofficeHandlerException;
import com.ebraga.trackerclub.android.handler.service.LoginServiceHandler;
import com.ebraga.trackerclub.android.handler.service.ParameterServiceHandler;
import com.ebraga.trackerclub.android.util.AndroidApplication;
import com.ebraga.trackerclub.android.util.ISmartServiceConstants;
import com.ebraga.trackerclub.android.util.SmartServiceJavascriptInterface;
import com.ebraga.trackerclub.android.util.UtilView;
import com.ebraga.trackerclub.android.util.api.AndroidContext;
import com.ebraga.trackerclub.android.util.core.AndroidContextImpl;
import com.ebraga.trackerclub.android.util.enumeration.AndroidConfigurationParameterName;
import com.ebraga.trackerclub.android.view.service.SyncDataService;
import com.ebraga.trackerclub.android.vo.ParameterVO;
import com.ebraga.trackerclub.android.vo.UserVO;

@SuppressLint("SetJavaScriptEnabled")
public class LoginActivity extends Activity {
	
	WebView webView;
	AndroidContext androidContext;
	UtilView utilView = new UtilView();
	UserVO userVO;
	private final long WAIT_TIME = 120000;

	private LoginServiceHandler loginServiceHandler() {
		androidContext = new AndroidContextImpl();
		   
		androidContext.setContext(getApplicationContext());				

		LoginServiceHandler loginServiceHandler = new LoginServiceHandler(androidContext);
		return loginServiceHandler;
	}
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_webview);

        webView = (WebView) findViewById(R.id.webview);
        webView.setWebViewClient(new MyWebViewClient());
        webView.getSettings().setBuiltInZoomControls(false);
        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JavascriptInterface(this.getBaseContext()), "AndroidNativeCode");

       	starServices();        
        
        if (checkNewVersion()) {
        	webView.loadUrl("file:///android_asset/version.html");
        } else {
        
	        if (validate()) {
	        	
		       	webView.loadUrl("file:///android_asset/welcome.html");
		       	
	        } else {
	        	
	        	webView.loadUrl("file:///android_asset/restriction.html");
	        	
	        }
        }
       	
    }
    

    @Override
    public void onDestroy() {
    	super.onDestroy();
    }    


	private void starServices() {
		/*
		Intent positionIntent = new Intent(getBaseContext(), PositionService.class);
		getBaseContext().startService(positionIntent);
		*/
		Intent syncIntent = new Intent(getBaseContext(), SyncDataService.class);
		getBaseContext().startService(syncIntent);
	}
    
	private boolean checkNewVersion() {
		try {
			
			androidContext = new AndroidContextImpl();
			androidContext.setContext(getApplicationContext());				
			ParameterServiceHandler parameterServiceHandler = new ParameterServiceHandler(androidContext);
		
			ParameterVO parameterVO = parameterServiceHandler.getParameter(AndroidConfigurationParameterName.VERSION_APP.getName());
			
			if (!parameterVO.getValue().equals(ISmartServiceConstants.VERSION_INFO.VERSION_APP)) {
				return true;
			} else {
				return false;
			}
			
		} catch (BackofficeHandlerException e) {
			return false;
		}

	}
	
    private boolean validate() {
    	
        boolean isValid = true;
        /*
		if (!UtilView.connectedToNetwork(getBaseContext())) {
			UtilView.sendNotification(getBaseContext(), getString(R.string.warn_internet_off));
			isValid = false;
		}
		*/
		
		if (!UtilView.gpsActived(getBaseContext())) {
			UtilView.sendNotification(getBaseContext(), getString(R.string.warn_gps_off), ISmartServiceConstants.NOTIFICATION_ID.GPS_DISABLED);
			isValid = false;
		}	        
		
		return isValid;
        
    }
    
	private void loginOffLine() throws BackofficeHandlerException {
		LoginServiceHandler loginServiceHandler = loginServiceHandler();
		loginServiceHandler.loginOffline(userVO);
		startActivity();
	}    
    
    private void startActivity() {
    	try {
    		
    		utilView.hideWaitMessage();
		
		} catch (Exception e) {
			Log.d(getPackageName(), e.getMessage());
		}	
    	
    	Intent intent = new Intent(getBaseContext(), MainActivity.class);
    	startActivity(intent);
    	setSessionUserVO();
    	
    	finish();
    	onDestroy();
				
    }
    

	public class JavascriptInterface extends SmartServiceJavascriptInterface {
		 
		public JavascriptInterface(Context c) {
			super(c);
		}

		public void lastLoginInfo() {
			try {
				UserVO userVO = UtilView.getLastUserSession(getBaseContext());
				
				String name 	= "";
				String brand 	= "";
				String model 	= "";
				
				JSONObject jObject = new JSONObject();
				if (userVO != null) {
					
					name = userVO.getName();
					brand = userVO.getBrand();
					model =  userVO.getModel();
					
					jObject.put("Name", name);
					jObject.put("Brand", brand);
					jObject.put("Model", model);
				}
				
				jObject.put("Name", name);
				jObject.put("Brand", brand);
				jObject.put("Model", model);				
	
				webView.loadUrl("javascript:setUserData(" + jObject + ")");
			
			} catch (Exception e) {

				Log.d(getPackageName(), e.getMessage());
				
			}			
			
		}
		
		public void login(String jsonString) {
			try {

				utilView.showWaitMessage(LoginActivity.this, WAIT_TIME);

				Log.d(getPackageName(), "Json enviados pela WebView: " + jsonString);

				Log.d(getPackageName(), "MAIN STORAGE: " + Environment.getExternalStorageState());
				//DebugUtils.backupDbToSdCard(LoginActivity.this);

				JSONObject jsonObject = new JSONObject(jsonString);
				String name = jsonObject.getString("name");
				String brand = jsonObject.getString("brand");
				String model = jsonObject.getString("model");
				
				userVO = new UserVO();
				userVO.setImei(UtilView.getIMEINumber(getApplicationContext()));
				userVO.setBrand(brand);
				userVO.setModel(model);
				userVO.setName(name);
				userVO.setLastLogin(new Date().getTime());
				
				if (name == null || name.equals(""))  {
					throw new AndroidViewException(ISmartServiceConstants.ERROR_CODE.INVALID_NAME);
				}
				
				if (model == null || model.equals(""))  {
					throw new AndroidViewException(ISmartServiceConstants.ERROR_CODE.INVALID_MODEL);
				}
				
				if (brand == null || brand.equals(""))  {
					throw new AndroidViewException(ISmartServiceConstants.ERROR_CODE.INVALID_BRAND);
				}
								
				
				loginOffLine();

			} catch (Exception e) {          
				utilView.hideWaitMessage();
				UtilView.showMessage(webView, getBaseContext(), e.getMessage());
				
			} finally {
				//utilView.hideWaitMessage();
			}
		}


		public void checkLastLogin() {
			try {
				
				webView.loadUrl("javascript:redirectLoginPage()");
				/*
				
				LoginServiceHandler loginServiceHandler = loginServiceHandler();

				userVO = loginServiceHandler.checkLastLogin();

				if (userVO != null) {
					
					Intent intent = new Intent(getBaseContext(), MainActivity.class);
					
					startActivity(intent);
					setSessionUserVO();
					
					finish();
					onDestroy();
					
				} else {
					
					webView.loadUrl("javascript:redirectLoginPage()");
					
				}
				*/

			} catch (Exception e) {
				UtilView.showMessage(webView, getBaseContext(), e.getMessage());
			}
		}		

	}    
	
	private void setSessionUserVO() {
		
		AndroidApplication androidApplication  = (AndroidApplication) getBaseContext().getApplicationContext();
		if (androidApplication != null) {
			androidApplication.setUserVO(userVO);
		}
		
	}


     
}